<?php
namespace App\Models\Goods;

use DB;

use App\Models\Goods\GoodsSale;

use App\Models\Goods\GoodsStore;

use App\Models\Goods\GoodsMarktingStrategy;

use App\Models\ConfigureFunction;

use Illuminate\Database\Eloquent\Model;

use App\Service\PromotionService;

use App\Models\SysTag;

use App\Models\ConfigureTagRelation;

use App\Models\ConfigureTag;

class GoodsMaster extends Model
{

    protected $table = 'goods_master';

    protected $primaryKey = 'mainPostID';

    public $timestamps = false;

    public $incrementing = false;


    /**
     * 查询商品主表商品数据
     */
    public static function getList( $arg_array )
    {

        //sql字符串
        $sql = '';

        //分类sql
        $category_sql = '';

        //参数值数组
        $params_array = array();

        $return_data = array(
            'count' => 0,
            'data' => array()
        );

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //品牌
        if (isset($arg_array['brandID']) && ebsig_is_int($arg_array['brandID'])) {
            $sql .= ' AND gm.brandID = ?';
            $params_array[] = $arg_array['brandID'];
        }

        //pc
        if (isset($arg_array['PC']) && ebsig_is_int($arg_array['PC'])) {
            $sql .= ' AND gm.PC = ?';
            $params_array[] = $arg_array['PC'];
        }

        //wap
        if (isset($arg_array['WAP']) && ebsig_is_int($arg_array['WAP'])) {
            $sql .= ' AND gm.WAP = ?';
            $params_array[] = $arg_array['WAP'];
        }

        //app
        if (isset($arg_array['APP']) && ebsig_is_int($arg_array['APP'])) {
            $sql .= ' AND gm.APP = ?';
            $params_array[] = $arg_array['APP'];
        }

        //按品牌筛选
        if ( isset($arg_array['brand']) && !empty($arg_array['brand']) ) {
            $str = '';
            foreach ( $arg_array['brand'] as $item ) {
                if (ebsig_is_int($item)) {
                    $str .= " OR  gm.brandID = $item";
                }
            }
            $str = ltrim(trim($str), 'OR ');
            $sql .= ' AND ' .'(' . $str . ')';
        }

        //分类
        if (isset($arg_array['bigCategoryID']) && ebsig_is_int($arg_array['bigCategoryID'])) {
            $category_sql .= ' AND bigCategoryID = ' . $arg_array['bigCategoryID'];
        }
        if (isset($arg_array['midCategoryID']) && ebsig_is_int($arg_array['midCategoryID'])) {
            $category_sql .= ' AND midCategoryID = ' . $arg_array['midCategoryID'];
        }
        if (isset($arg_array['smallCategoryID']) && ebsig_is_int($arg_array['smallCategoryID'])) {
            $category_sql .= ' AND smallCategoryID = ' . $arg_array['smallCategoryID'];
        }

        //销售状态
        $sql .= ' AND gm.forsale = 1 AND gm.useFlg = 1 AND wm.storeID = ' . $arg_array['shop_id'];
        $sql = ' WHERE ' . substr($sql, 4);

        if ($category_sql) {
            $category_sql = ' WHERE ' . substr($category_sql, 4);
        }

        //统计数量
        $count_sql = 'SELECT COUNT(gm.mainPostID) AS c FROM goods_master gm 
                      INNER JOIN ( SELECT DISTINCT mainPostID FROM goods_extend_category ' . $category_sql . ' ) AS gec ON gec.mainPostID = gm.mainPostID
                      INNER JOIN wms_goods_master wm ON wm.mainPostID = gm.mainPostID' . $sql;
        $count_array = DB::select($count_sql, $params_array);
        $return_data['count'] = $count_array[0]['c'];
        if ($return_data['count'] == 0) {
            return $return_data;
        }

        //排序
        if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {

            if (!isset($arg_array['sortorder']) || !in_array($arg_array['sortorder'], array('ASC', 'DESC', 'asc', 'desc'))) {
                $arg_array['sortorder'] = 'ASC';
            } else {
                $arg_array['sortorder'] = strtoupper($arg_array['sortorder']);
            }
            $sql .= sprintf(' ORDER BY gm.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //分页
        if (!isset($arg_array['page']) || !ebsig_is_int($arg_array['page']))
            $arg_array['page'] = 1;
        if (!isset($arg_array['rp']) || !ebsig_is_int($arg_array['rp'])) {
            $arg_array['rp'] = 10;
        }
        $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        //查询商品数据
        $search_sql = 'SELECT gm.* FROM goods_master gm
                       INNER JOIN ( SELECT DISTINCT mainPostID FROM goods_extend_category ' . $category_sql . ' ) AS gec ON gec.mainPostID = gm.mainPostID
                       INNER JOIN wms_goods_master wm ON wm.mainPostID = gm.mainPostID ' . $sql;

        $return_data['data'] = DB::select($search_sql, $params_array);

        foreach($return_data['data'] as &$goods) {

            $goods['enableSaleAmount'] = 0;

            $goods_sale_data = GoodsSale::select('product_code','postID','product_spec','virtual_id')->where(['mainPostID'=>$goods['mainPostID'],'forsale'=>1])->get()->toArray();
            foreach($goods_sale_data as &$sale_goods) {
                $goods['virtual_id'] = $sale_goods['virtual_id'];
                $enableSaleAmount = GoodsStore::search($sale_goods['product_code'], $sale_goods['product_spec'], $arg_array['shop_id']);
                if ( $enableSaleAmount > 0 ) {
                    $goods['enableSaleAmount'] = $enableSaleAmount;
                    $goods['postID'] = $sale_goods['postID'];
                    break;
                }
            }

            $goods['spec_num'] = count($goods_sale_data);
            $goods['link'] = set_goods_link($goods['postID']);
            $goods['wap_link'] = set_wap_goods_link($goods['postID']);
            $goods['img_link'] = $domain_url . $goods['goodsMainPic'];

            if ( $arg_array['shop_id'] > 0 ) {
                $goods_markting_strategy = GoodsMarktingStrategy::where(['shop_id' => $arg_array['shop_id'],'postID' => $goods['postID']])->first();
                if ($goods_markting_strategy) {
                    $goods_markting_strategy = $goods_markting_strategy->toArray();
                    $goods['marketPrice'] = $goods_markting_strategy['marketPrice'];
                    $goods['salePrice'] = $goods_markting_strategy['salePrice'];
                    $goods['salePoints'] = $goods_markting_strategy['salePoints'];
                }
            }

        }

        return $return_data;

    }


    /**
     * 根据关键词查询商品主表
     */
    public static function getListByKeyword( $arg_array )
    {

        //sql字符串
        $sql = '';

        //参数值数组
        $params_array = array();

        $return_data = array(
            'count' => 0,
            'data' => array()
        );

        $domain_url = ConfigureFunction::getConfigureField(43, 'domain_url');

        //检查关键词
        if (!isset($arg_array['keyword']) || empty($arg_array['keyword'])) {
            return $return_data;
        }
        $sql .= ' AND gm.goodsName LIKE ?';
        $params_array[] = '%' . $arg_array['keyword'] . '%';

        //品牌
        if (isset($arg_array['brandID']) && ebsig_is_int($arg_array['brandID'])) {
            $sql .= ' AND gm.brandID = ?';
            $params_array[] = $arg_array['brandID'];
        }

        //pc
        if (isset($arg_array['PC']) && ebsig_is_int($arg_array['PC'])) {
            $sql .= ' AND gm.PC = ?';
            $params_array[] = $arg_array['PC'];
        }

        //wap
        if (isset($arg_array['WAP']) && ebsig_is_int($arg_array['WAP'])) {
            $sql .= ' AND gm.WAP = ?';
            $params_array[] = $arg_array['WAP'];
        }

        //app
        if (isset($arg_array['APP']) && ebsig_is_int($arg_array['APP'])) {
            $sql .= ' AND gm.APP = ?';
            $params_array[] = $arg_array['APP'];
        }

        //销售状态
        $sql .= ' AND gm.forsale = 1 AND gm.useFlg = 1';
        $sql = ' WHERE ' . substr($sql, 4);

        //统计数量
        $count_sql = 'SELECT COUNT(gm.mainPostID) AS c FROM goods_master gm
                      INNER JOIN wms_goods_master wm ON wm.storeID = ' . $arg_array['shop_id'] . ' AND wm.mainPostID = gm.mainPostID' . $sql;
        $count_array = DB::select($count_sql, $params_array);
        $return_data['count'] = $count_array[0]['c'];
        if ($return_data['count'] == 0) {
            return $return_data;
        }

        //排序
        if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {

            if (!isset($arg_array['sortorder']) || !in_array($arg_array['sortorder'], array('ASC', 'DESC', 'asc', 'desc'))) {
                $arg_array['sortorder'] = 'ASC';
            } else {
                $arg_array['sortorder'] = strtoupper($arg_array['sortorder']);
            }
            $sql .= sprintf(' ORDER BY gm.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

        }

        //分页
        if (!isset($arg_array['page']) || !ebsig_is_int($arg_array['page']))
            $arg_array['page'] = 1;
        if (!isset($arg_array['rp']) || !ebsig_is_int($arg_array['rp'])) {
            $arg_array['rp'] = 10;
        }
        $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

        //查询商品数据
        $search_sql = 'SELECT gm.* FROM goods_master gm
                      INNER JOIN wms_goods_master wm ON wm.storeID = ' . $arg_array['shop_id'] . ' AND wm.mainPostID = gm.mainPostID ' . $sql;

        $return_data['data'] = DB::select($search_sql, $params_array);

        foreach($return_data['data'] as &$goods) {

            $goods['enableSaleAmount'] = 0;

            $goods_sale_data = GoodsSale::select('product_code','postID','product_spec','virtual_id')->where(['mainPostID'=>$goods['mainPostID'],'forsale'=>1])->get()->toArray();
            foreach($goods_sale_data as &$sale_goods) {
                $goods['virtual_id'] = $sale_goods['virtual_id'];
                $enableSaleAmount = GoodsStore::search($sale_goods['product_code'], $sale_goods['product_spec'], $arg_array['shop_id']);
                if ( $enableSaleAmount > 0 ) {
                    $goods['enableSaleAmount'] = $enableSaleAmount;
                    $goods['postID'] = $sale_goods['postID'];
                    break;
                }
            }

            $goods['spec_num'] = count($goods_sale_data);
            $goods['link'] = set_goods_link($goods['postID']);
            $goods['wap_link'] = set_wap_goods_link($goods['postID']);
            $goods['img_link'] = $domain_url . $goods['goodsMainPic'];

            if ( $arg_array['shop_id'] > 0 ) {
                $goods_markting_strategy = GoodsMarktingStrategy::where(['shop_id' => $arg_array['shop_id'],'postID' => $goods['postID']])->first();
                if ($goods_markting_strategy) {
                    $goods_markting_strategy = $goods_markting_strategy->toArray();
                    $goods['marketPrice'] = $goods_markting_strategy['marketPrice'];
                    $goods['salePrice'] = $goods_markting_strategy['salePrice'];
                    $goods['salePoints'] = $goods_markting_strategy['salePoints'];
                }
            }

        }

        return $return_data;

    }

    /**
     * 查询随机N条商品数据
     * @param array $args_data 查询参数数组
     * @param int $pcustID 用户名
     * @param int $limit 查询条数，不超过10调
     * @param bool $is_choose_goods_by_mall 是否根据门店查询商品
     * @return array
     */
    public static function getRandGoods($args_data, $pcustID = 0, $limit = 10, $platform = 6) {

        //sql字符串
        $sql = '';

        //分类sql
        $category_sql = '';

        //参数值数组
        $params_array = array();

        if ($limit > 10) {
            $limit = 10;
        }

        //分类
        if (isset($args_data['bigCategoryID']) && ebsig_is_int($args_data['bigCategoryID'])) {
            $category_sql .= ' AND bigCategoryID = ' . $args_data['bigCategoryID'];
        }
        if (isset($args_data['midCategoryID']) && ebsig_is_int($args_data['midCategoryID'])) {
            $category_sql .= ' AND midCategoryID = ' . $args_data['midCategoryID'];
        }
        if (isset($args_data['smallCategoryID']) && ebsig_is_int($args_data['smallCategoryID'])) {
            $category_sql .= ' AND smallCategoryID = ' . $args_data['smallCategoryID'];
        }

        //扩展查询
        if (isset($args_data['extend_sql']) && !empty($args_data['extend_sql'])) {
            $sql .= $args_data['extend_sql'];
        }

        //销售状态
        $sql .= ' AND gm.forsale = 1 AND gm.useFlg = 1';

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        if ($category_sql) {
            $category_sql = ' WHERE ' . substr($category_sql, 4) ;
        }

        //查询商品数据
        $search_sql = 'SELECT gm.* FROM goods_master gm 
                                INNER JOIN ( SELECT DISTINCT mainPostID FROM goods_extend_category ' . $category_sql . ' ) AS gec ON gec.mainPostID = gm.mainPostID' . $sql . ' ORDER BY RAND() LIMIT 50';
        $goods_data = DB::select($search_sql, $params_array);


        if (!$goods_data) {
            return null;
        }

        $return_goods_data = array();
        foreach ($goods_data as &$goods) {

            $goods['enableSaleAmount'] = 0;

            $goods_sale_data = GoodsSale::where(['mainPostID' => $goods['mainPostID'], 'forsale' => 1])->get()->toArray();
            foreach($goods_sale_data as &$sale_goods) {
                $enableSaleAmount = GoodsStore::search($sale_goods['product_code'], $sale_goods['product_spec'], $args_data['shop_id']);
                if ($enableSaleAmount > 0) {
                    $goods['enableSaleAmount'] = $enableSaleAmount;
                    $goods['postID'] = $sale_goods['postID'];
                    break;
                }
            }

            if ( $args_data['shop_id'] > 0 ) {
                $priceData = GoodsMarktingStrategy::where(['shop_id' => $args_data['shop_id'], 'postID' => $goods['postID']])->first();
                if( $priceData ) {
                    $priceData = $priceData->toArray();
                    $goods['marketPrice'] = $priceData['marketPrice'];
                    $goods['salePrice'] = $priceData['salePrice'];
                    $goods['salePoints'] = $priceData['salePoints'];
                }
            }

            $tag_data = [];

            //商品促销查询
            $promotion_data = PromotionService::goods(array(
                'postID' => $goods['postID'],
                'salePrice' => $goods['salePrice'],
                'salePoints' => isset($goods['salePoints']) ? $goods['salePoints'] : 0,
                'product_code' => $goods['product_code'],
                'marketPrice' => $goods['marketPrice'],
                'goods_amount' => 1,
                'pcustID' => $pcustID,
                'mallareaID' => $args_data['mall_area_id'],
                'mallID' => $args_data['mallID'],
                'platform' => $platform
            ));
            if (isset($promotion_data['promotion']) && !empty($promotion_data['promotion'])) {
                $price = $goods['salePrice'];
            } else {
                $price = $promotion_data['price'];
                if (isset($promotion_data['promotion']) && !empty($promotion_data['promotion'])) {
                    foreach ($promotion_data['promotion'] as $p) {
                        if (isset($p['selected']) && $p['selected'] == 1) {
                            $res_data = SysTag::getCache($p['promotion_type']); //查询商品标签信息
                            if ($res_data) {
                                $tag_data[] = $res_data;
                            }
                        }
                    }
                }
            }

            //查询商品标签
            $tag_relation_data = ConfigureTagRelation::where(['relation_id'=>$goods['mainPostID'],'relation_type'=>1])->get()->toArray();
            if ($tag_relation_data) {
                foreach ($tag_relation_data as $tag) {
                    $reslut_data = ConfigureTag::where(['tag_id'=>$tag['tag_id']])->first();
                    if ($reslut_data) {
                        $reslut_data = $reslut_data->toArray();
                        $tag_data[] = $reslut_data;
                    }
                }
            }

            $return_goods_data[] = array(
                'mainPostID' => $goods['mainPostID'],
                'postID' => $goods['postID'],
                'goodsName' => $goods['goodsName'],
                'salePrice' => round($goods['salePrice'], 2),
                'marketPrice' => round($goods['marketPrice'], 2),
                'img_link' => $goods['goodsMainPic'],
                'price' => round($price, 2),
                'enableSaleAmount' => $goods['enableSaleAmount'],
                'tag' => $tag_data,
                'spec_num' => count($goods_sale_data)
            );

            if (isset($return_goods_data[$limit-1])) {
                break;
            }

        }

        return $return_goods_data;

    }

}
